package com.yrk.dao.impl;

import com.yrk.dao.UserDao;
import com.yrk.entity.User;
import com.yrk.unity.GetConn;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    Connection conn = GetConn.getConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    public boolean addUser(String username, String password,String tel,String sex){
        boolean flag = false;
        try{
            String sql="insert into user (username,password,tel,sex) values(?,?,?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,tel);
            ps.setString(4,sex);
            int n=ps.executeUpdate();
            if(n>0){
                flag=true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            GetConn.closeAll(conn,ps,rs);
        }
        return flag;
    }
    public List<User> getUsers(){
        List<User> list = new ArrayList<User>();
        try {
            String  sql="select * from user";
            conn=GetConn.getConnection();
            ps =conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                User user=new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTel(rs.getString("tel"));
                user.setSex(rs.getString("sex"));
                list.add(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public User findUserByUserName(String userName) {
        String sql="select * from user where username=?";
        User user=new User();
        try{
            ps=conn.prepareStatement(sql);
            ps.setString(1,userName);
            rs=ps.executeQuery();
            if(rs.next()){
                user.setPassword(rs.getString("password"));
                user.setUsername(userName);
            }else{
                user=null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public boolean checkUserName(String userName) {
        boolean flag = false;
        try {
            ps=conn.prepareStatement("select username from user where username=?");
            ps.setString(1,userName);
            rs=ps.executeQuery();
            if(rs.next()){
                flag=true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }
}
